package com.quectel.cms.controller.partybuildingsurvey;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.partybuilding.PartyPersonMsgBusiness;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.cms.vo.PartySurveyShareRsp;
import com.quectel.constant.PushConstants;
import com.quectel.constant.core.mobileuser.MobileUserMsgConstants;
import com.quectel.constant.core.partybuilding.PartyBuildingConstants;
import com.quectel.constant.core.partybuilding.PartySurveyConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.constant.sys.SysConfigKeyConstants;
import com.quectel.core.module.mobileuser.dto.MobileUserDto;
import com.quectel.core.module.mobileuser.service.MobileUserService;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonResp;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.core.module.partybuildingsurvey.dto.*;
import com.quectel.core.module.partybuildingsurvey.service.*;
import com.quectel.sys.module.sys.service.SysConfigService;
import com.quectel.util.common.*;
import com.quectel.util.kit.PageFetchKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:38
 */
@RestController
@RequestMapping("partySurvey")
@Tag(name = "PartySurveyController", description = "问卷调查管理相关api")
public class PartySurveyController extends BaseController {

    @DubboReference
    private PartySurveyService partySurveyService;

    @DubboReference
    private PartyPersonService partyPersonService;
    @DubboReference
    private PartySurveyPersonBindingService partySurveyPersonBindingService;
    @DubboReference
    private PartySurveyQuestionService partySurveyQuestionService;
    @DubboReference
    private PartySurveyPersonRecordService partySurveyPersonRecordService;
    @DubboReference
    private PartySurveyPersonAnswerService partySurveyPersonAnswerService;
    @DubboReference
    private SysConfigService sysConfigService;
    @DubboReference
    private MobileUserService mobileUserService;
    @Autowired
    private PartyPersonMsgBusiness partyPersonMsgBusiness;


    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("notify/{id}")
    @RequirePermissions(values = "partySurvey:info")
    @Operation(summary = "调查问卷通知用户")
    public Response notify(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (partySurveyService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartySurveyDto partySurveyDto = partySurveyService.selectById(id);

        //如果未发布则不可以通知
        if (!PartySurveyConstants.MarkStatus.PUBLISHED.getStatus().equals(partySurveyDto.getStatus())) {
            return Response.error("未发布问卷不能发布通知");
        }

        List<PartySurveyPersonBindingDto> partySurveyPersonBindingDtos = partySurveyPersonBindingService.selectBySurveyId(partySurveyDto.getId());
        partySurveyDto.setBindPerson(partySurveyPersonBindingDtos);

        if (CollectionUtils.isEmpty(partySurveyPersonBindingDtos)) {
            return Response.ok();
        }

        for (PartySurveyPersonBindingDto partySurveyPersonBindingDto : partySurveyPersonBindingDtos) {
            PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(partySurveyPersonBindingDto.getPersonId());
            if (partyPersonDto == null) {
                continue;
            }

            MobileUserDto mobileUserDto = mobileUserService.selectByMobile(partyPersonDto.getMobile());
            if (mobileUserDto == null) {
                continue;
            }

            partyPersonMsgBusiness.pushMsg(
                    partySurveyDto.getTenantId(),
                    Collections.singletonList(mobileUserDto),
                    PartySurveyConstants.Category.DEMOCRATIC_VOTING.getCategory().equals(partySurveyDto.getCategory()) ? MobileUserMsgConstants.SourceType.PARTY_SURVEY_PUBLIC_OPINION_SURVEY_MSG : MobileUserMsgConstants.SourceType.PARTY_SURVEY_DEMOCRATIC_VOTING_MSG,
                    partySurveyDto.getId(),
                    PartySurveyConstants.Category.DEMOCRATIC_VOTING.getCategory().equals(partySurveyDto.getCategory()) ? PartyBuildingConstants.PARTY_SURVEY_PUBLIC_OPINION_SURVEY_MSG_TITLE : PartyBuildingConstants.PARTY_SURVEY_DEMOCRATIC_VOTING_MSG_TITLE,
                    partySurveyDto.getName(),
                    true,
                    new PushConstants.PushType[]{PushConstants.PushType.WECHAT_OFFICIAL}
            );
        }


        return Response.ok();
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("share/{id}")
    @RequirePermissions(values = "partySurvey:info")
    @Operation(summary = "查看调查问卷分享详情")
    public Response<PartySurveyShareRsp> share(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (partySurveyService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartySurveyDto partySurveyDto = partySurveyService.selectById(id);
        PartySurveyShareRsp partySurveyShareRsp = new PartySurveyShareRsp();
        partySurveyShareRsp.setId(partySurveyDto.getId());
        partySurveyShareRsp.setName(partySurveyDto.getName());
        partySurveyShareRsp.setPartyName(partySurveyDto.getPartyName());
        partySurveyShareRsp.setStartTime(partySurveyDto.getStartTime());
        partySurveyShareRsp.setEndTime(partySurveyDto.getEndTime());
        String gateway = sysConfigService.getConfigValueByKey(SysConfigKeyConstants.MOBILE_USER_WEB_URL);
        if (PartySurveyConstants.Category.PUBLIC_OPINION_SURVEY.getCategory().equals(partySurveyDto.getCategory())) {
            partySurveyShareRsp.setLink(gateway + PartySurveyConstants.PEOPLE_POLL + partySurveyDto.getId());
        }
        if (PartySurveyConstants.Category.DEMOCRATIC_VOTING.getCategory().equals(partySurveyDto.getCategory())) {
            partySurveyShareRsp.setLink(gateway + PartySurveyConstants.PEOPLE_VOTE + partySurveyDto.getId());
        }

        return Response.<PartySurveyShareRsp>ok().wrap(partySurveyShareRsp);
    }


    /**
     * 查看填空题详情
     *
     * @param pageNo
     * @param pageSize
     * @param partySurveyId
     * @param questionId
     * @return
     */
    @GetMapping("queryAnswer")
    @Operation(summary = "查询问卷答题详情,根据类型查询")
    @RequirePermissions(values = "partySurvey:statistics")
    public Response<Page<PartySurveyPersonAnswerDto>> queryAnswer(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "调查id") @RequestParam Long partySurveyId,
            @Parameter(description = "题目id") @RequestParam Long questionId,
            @Parameter(description = "选项id") @RequestParam(required = false) Long answerId,
            @Parameter(description = "查询条件,如果是填空题,支持模糊查询,如果是评分题,则传值为1,2,3") @RequestParam(required = false) String queryParam

    ) {

        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        PartySurveyQuestionDto partySurveyQuestionDto = partySurveyQuestionService.selectCacheById(questionId);
        if (partySurveyQuestionDto == null) {
            return Response.error("未查询到该问题");
        }

        request.put(LambdaUtil.getFieldName(PartySurveyPersonAnswerDto::getPartySurveyId), partySurveyId);
        request.put(LambdaUtil.getFieldName(PartySurveyPersonAnswerDto::getQuestionId), questionId);
        request.put(PartySurveyConstants.QUESTION_TYPE, partySurveyQuestionDto.getType());

        request.put(PartySurveyConstants.ANSWER_ID, answerId);

        if (PartySurveyConstants.QuestionType.BLANK.getType().equals(partySurveyQuestionDto.getType())) {
            request.put(PartySurveyConstants.QUERY_PARAM, queryParam);
        }
        if (PartySurveyConstants.QuestionType.EVALUATE.getType().equals(partySurveyQuestionDto.getType()) && StringUtils.isNotBlank(queryParam)) {
            int[] intArr = Arrays.stream(queryParam.split(",")).mapToInt(Integer::parseInt).toArray();
            request.put(PartySurveyConstants.SCORES, intArr);
        }


        int total = partySurveyPersonAnswerService.queryTotal(request.getParams());

        List<PartySurveyPersonAnswerDto> list = null;
        if (total > 0) {
            list = partySurveyPersonAnswerService.queryList(request.getParams());
            list.forEach(partySurveyPersonAnswerDto -> {

                PartySurveyPersonRecordDto partySurveyPersonRecordDto = partySurveyPersonRecordService.selectCacheById(partySurveyPersonAnswerDto.getRecordId());
                if (partySurveyPersonRecordDto != null) {
                    PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(partySurveyPersonRecordDto.getPersonId());
                    if (SystemConstants.YES.equals(partySurveyPersonRecordDto.getAnonymous())) {
                        partySurveyPersonAnswerDto.setPersonName("匿名");
                    } else {
                        partySurveyPersonAnswerDto.setPersonName(partyPersonDto.getName());
                    }
                }

            });
        } else {
            list = new ArrayList<>();
        }

        Page<PartySurveyPersonAnswerDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<PartySurveyPersonAnswerDto>>ok().wrap(page);
    }

    /**
     * 查看答题详情
     *
     * @param partySurveyId
     * @param personId
     * @return
     */
    @GetMapping("infoPersonResult")
    @Operation(summary = "查询人员答题详情,查询结果为最后一次答题记录")
    @RequirePermissions(values = "partySurvey:statistics")
    public Response<PartySurveyPersonRecordDto> infoPersonResult(
            @Parameter(description = "调查id") @RequestParam("partySurveyId") Long partySurveyId,
            @Parameter(description = "是否查看结果") @RequestParam Long personId
    ) {
        Map<String, Object> params = new HashMap<>();
        Request request = Request.configParams(params);

        request.getParams().put(LambdaUtil.getFieldName(PartySurveyDto::getId), partySurveyId);
        request.getParams().put(LambdaUtil.getFieldName(PartySurveyDto::getTenantId), SessionHolder.getSysUser().getTenantId());

        if (partySurveyService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartySurveyDto partySurveyDto = partySurveyService.selectCacheById(partySurveyId);

        //查询是否参加
        PartySurveyPersonBindingDto partySurveyPersonBindingDto = partySurveyPersonBindingService.selectBySurveyIdAndPersonId(partySurveyDto.getId(), personId);
        if (partySurveyPersonBindingDto == null || SystemConstants.NO.equals(partySurveyPersonBindingDto.getParticipateStatus())) {
            return Response.error("未查询到记录");
        }

        //查询最新一次答题记录
        PartySurveyPersonRecordDto partySurveyPersonRecordDto = partySurveyPersonRecordService.selectLastBySurveyIdAndPersonId(partySurveyDto.getId(), personId);
        if (partySurveyPersonRecordDto == null) {
            return Response.error("未查询到记录");
        }
        List<PartySurveyPersonAnswerDto> partySurveyPersonAnswerDtos = partySurveyPersonAnswerService.selectByRecordId(partySurveyPersonRecordDto.getId());
        Map<Long, PartySurveyPersonAnswerDto> collect = partySurveyPersonAnswerDtos.stream().collect(Collectors.toMap(PartySurveyPersonAnswerDto::getQuestionId, Function.identity(), (key1, key2) -> key2));

        List<PartySurveyQuestionDto> partySurveyQuestionDtos = new ArrayList<>(partySurveyDto.getBindQuestion().size());
        //将题目和答案组装
        partySurveyDto.getBindQuestion().forEach(
                partySurveyQuestionDto -> {
                    PartySurveyPersonAnswerDto partySurveyPersonAnswerDto = collect.get(partySurveyQuestionDto.getId());
                    partySurveyQuestionDto.setPartySurveyPersonAnswer(partySurveyPersonAnswerDto);

                    //允许查询结果
                    if (SystemConstants.YES.equals(partySurveyDto.getKnowResult())) {
                        partySurveyQuestionDto = partySurveyQuestionService.questionCount(partySurveyQuestionDto);
                    }
                    partySurveyQuestionDtos.add(partySurveyQuestionDto);
                }
        );
        partySurveyDto.setBindQuestion(partySurveyQuestionDtos);
        partySurveyPersonRecordDto.setPartySurvey(partySurveyDto);

        return Response.<PartySurveyPersonRecordDto>ok().wrap(partySurveyPersonRecordDto);
    }


    /**
     * 查看答题详情
     *
     * @param partySurveyId
     * @param showResult
     * @return
     */
    @GetMapping("infoSurvey")
    @Operation(summary = "查询问卷详情")
    @RequirePermissions(values = "partySurvey:statistics")
    public Response<PartySurveyDto> infoSurvey(
            @Parameter(description = "调查id") @RequestParam Long partySurveyId,
            @Parameter(description = "是否查看结果") @RequestParam(value = "showResult", required = false) Byte showResult
    ) {

        Map<String, Object> params = new HashMap<>();
        Request request = Request.configParams(params);

        request.getParams().put(LambdaUtil.getFieldName(PartySurveyDto::getId), partySurveyId);
        request.getParams().put(LambdaUtil.getFieldName(PartySurveyDto::getTenantId), SessionHolder.getSysUser().getTenantId());

        if (partySurveyService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartySurveyDto partySurveyDto = partySurveyService.selectCacheById(partySurveyId);


        List<PartySurveyQuestionDto> partySurveyQuestionDtos = new ArrayList<>(partySurveyDto.getBindQuestion().size());
        //将题目和答案组装
        partySurveyDto.getBindQuestion().forEach(
                partySurveyQuestionDto -> {
                    //是否查询结果
                    if (SystemConstants.YES.equals(showResult)) {
                        partySurveyQuestionDto = partySurveyQuestionService.questionCount(partySurveyQuestionDto);
                    }
                    partySurveyQuestionDtos.add(partySurveyQuestionDto);
                }
        );
        partySurveyDto.setBindQuestion(partySurveyQuestionDtos);

        return Response.<PartySurveyDto>ok().wrap(partySurveyDto);
    }

    /**
     * 查看答题详情
     *
     * @param recordId
     * @return
     */
    @GetMapping("infoResult")
    @Operation(summary = "查询答题记录详情")
    @RequirePermissions(values = "partySurvey:statistics")
    public Response<PartySurveyPersonRecordDto> infoResult(
            @Parameter(description = "记录Id") @RequestParam(value = "recordId") Long recordId
    ) {
        //查询最新一次答题记录
        PartySurveyPersonRecordDto partySurveyPersonRecordDto = partySurveyPersonRecordService.selectById(recordId);
        if (partySurveyPersonRecordDto == null) {
            return Response.error("未查询到记录");
        }
        PartySurveyDto partySurveyDto = partySurveyService.selectCacheById(partySurveyPersonRecordDto.getPartySurveyId());

        List<PartySurveyPersonAnswerDto> partySurveyPersonAnswerDtos = partySurveyPersonAnswerService.selectByRecordId(partySurveyPersonRecordDto.getId());
        Map<Long, PartySurveyPersonAnswerDto> collect = partySurveyPersonAnswerDtos.stream().collect(Collectors.toMap(PartySurveyPersonAnswerDto::getQuestionId, Function.identity(), (key1, key2) -> key2));

        List<PartySurveyQuestionDto> partySurveyQuestionDtos = new ArrayList<>(partySurveyDto.getBindQuestion().size());
        //将题目和答案组装
        partySurveyDto.getBindQuestion().forEach(
                partySurveyQuestionDto -> {

                    PartySurveyPersonAnswerDto partySurveyPersonAnswerDto = collect.get(partySurveyQuestionDto.getId());
                    partySurveyQuestionDto.setPartySurveyPersonAnswer(partySurveyPersonAnswerDto);

                    partySurveyQuestionDto = partySurveyQuestionService.questionCount(partySurveyQuestionDto);
                    partySurveyQuestionDtos.add(partySurveyQuestionDto);
                }
        );
        partySurveyDto.setBindQuestion(partySurveyQuestionDtos);
        partySurveyPersonRecordDto.setPartySurvey(partySurveyDto);

        return Response.<PartySurveyPersonRecordDto>ok().wrap(partySurveyPersonRecordDto);
    }


    /**
     * 提前结束党建任务计划
     *
     * @param id
     * @return
     */
    @PostMapping("publish")
    @RequirePermissions(values = "partySurvey:edit")
    @Operation(summary = "发布党建任务计划")
    public Response<Object> publish(@RequestBody Long id) {
        //查询是否存在
        PartySurveyDto partySurveyDto = partySurveyService.selectById(id);
        if (partySurveyDto == null) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //未发布才可以发布
        if (!PartySurveyConstants.PartySurveyStatus.UN_PUBLISH.getStatus().equals(partySurveyDto.getPartySurveyStatus())) {
            return Response.error("当前问卷不能发布，只有未发布的问卷可以发布");
        }
        //覆盖结束时间
        partySurveyDto.setStatus(PartySurveyConstants.MarkStatus.PUBLISHED.getStatus());
        partySurveyService.updateById(partySurveyDto);

        return Response.ok();
    }


    /**
     * 提前结束调查问卷
     *
     * @param id
     * @return
     */
    @PostMapping("terminate")
    @RequirePermissions(values = "partySurvey:edit")
    @Operation(summary = "提前结束调查问卷")
    public Response<Object> terminate(@RequestBody Long id) {
        //查询是否存在
        PartySurveyDto partySurveyDto = partySurveyService.selectById(id);
        if (partySurveyDto == null) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //必须开始了才能提前结束
        if (!PartySurveyConstants.PartySurveyStatus.IN_PROGRESS.getStatus().equals(partySurveyDto.getPartySurveyStatus())) {
            return Response.error("当前问卷不能提前结束，只有已开始的问卷可以提前结束");
        }

        PartySurveyDto surveyDto = new PartySurveyDto();
        surveyDto.setId(partySurveyDto.getId());

        //结束时间为当前时间
        surveyDto.setEndTime(new Date());

        //覆盖结束时间
        partySurveyService.updateById(surveyDto);

        return Response.ok();
    }

    /**
     * 取消党建任务计划
     *
     * @param id
     * @return
     */
    @PostMapping("cancel")
    @RequirePermissions(values = "partySurvey:edit")
    @Operation(summary = "取消党建任务计划")
    public Response<Object> cancel(@RequestBody Long id) {
        //查询是否存在
        PartySurveyDto partySurveyDto = partySurveyService.selectById(id);
        if (partySurveyDto == null) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //未开始可以取消
        if (!PartySurveyConstants.PartySurveyStatus.NOT_START.getStatus().equals(partySurveyDto.getPartySurveyStatus())) {
            return Response.error("当前问卷不能取消，只有未开始的问卷可以取消");
        }

        //已经取消不用取消
        if (PartySurveyConstants.MarkStatus.CANCELED.getStatus().equals(partySurveyDto.getStatus())) {
            return Response.error("已经取消，无须再次取消");
        }

        PartySurveyDto surveyDto = new PartySurveyDto();
        surveyDto.setId(partySurveyDto.getId());
        surveyDto.setStatus(PartySurveyConstants.MarkStatus.CANCELED.getStatus());
        partySurveyService.updateById(surveyDto);

        return Response.ok();
    }


    /**
     * 导出记录
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "partySurvey:exportExcel")
    @Operation(summary = "导出问卷记录")
    @Log(express = "导出问卷记录")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<PartySurveyDto> result = PageFetchKit.fetchAll(r -> partySurveyService.queryList(r), request.getParams());

        String[] headers = new String[]{"问卷名称", "所属党组织", "问卷时间", "问卷统计", "问卷状态", "创建人", "创建时间", "编辑人", "编辑时间"};

        List<String> list = new ArrayList<>(Arrays.asList(headers));

        List<String[]> dataList = new ArrayList<>();
        for (PartySurveyDto data : result) {
            List<String> item = new ArrayList<>();
            item.add(data.getName());
            item.add(data.getPartyName());
            item.add(DateUtils.format(data.getStartTime(), DateUtils.FormatType.COMMON) + "~" + DateUtils.format(data.getEndTime(), DateUtils.FormatType.COMMON));
            int totalCount = 0;
            if (CollectionUtils.isNotEmpty(data.getBindPerson())) {
                totalCount = data.getBindPerson().size();
            }
            item.add(data.getParticipateCount() + "/" + totalCount);
            item.add(SysCodeUtils.easyToGetName(SysCodeKeyConstants.PARTY_SURVEY_STATUS, String.valueOf(data.getPartySurveyStatus())));
            item.add(data.getCreator());
            item.add(DateUtils.format(data.getCreateTime(), DateUtils.FormatType.COMMON));
            item.add(data.getEditor());
            item.add(DateUtils.format(data.getEditTime(), DateUtils.FormatType.COMMON));

            List<PartySurveyQuestionDto> partySurveyQuestionDtos = partySurveyQuestionService.selectBySurveyId(data.getId());
            List<PartySurveyQuestionDto> collect = partySurveyQuestionDtos.stream().sorted(Comparator.comparing(PartySurveyQuestionDto::getSort)).collect(Collectors.toList());
            for (PartySurveyQuestionDto questionDto : collect) {
                questionDto = partySurveyQuestionService.questionCount(questionDto);
                list.add("Q" + questionDto.getSort() + "_" + questionDto.getName());
                StringBuffer stringBuffer = new StringBuffer();
                if (PartySurveyConstants.QuestionType.SINGLE_CHOICE.getType().equals(questionDto.getType())
                        || PartySurveyConstants.QuestionType.MULTIPLE_CHOICE.getType().equals(questionDto.getType())
                        || PartySurveyConstants.QuestionType.PIC_SINGLE_CHOICE.getType().equals(questionDto.getType())
                        || PartySurveyConstants.QuestionType.PIC_MULTIPLE_CHOICE.getType().equals(questionDto.getType())
                ) {
                    stringBuffer.append("总答题数:").append(questionDto.getAnswerCount()).append("|");
                    if (CollectionUtils.isNotEmpty(questionDto.getBindAnswer())) {
                        questionDto.getBindAnswer().forEach(partySurveyAnswerDto -> {
                            stringBuffer.append("选项").append(partySurveyAnswerDto.getSort()).append(":").append(partySurveyAnswerDto.getContent()).append("答题人数:").append(partySurveyAnswerDto.getAnswerCount()).append("|");
                        });
                    }
                }
                if (PartySurveyConstants.QuestionType.BLANK.getType().equals(questionDto.getType())) {
                    stringBuffer.append("总答题数:").append(questionDto.getAnswerCount()).append("|");
                }
                if (PartySurveyConstants.QuestionType.EVALUATE.getType().equals(questionDto.getType())) {
                    stringBuffer.append("总答题数:" + questionDto.getAnswerCount()).append("|");
                    if (questionDto.getBindAnswer() != null && questionDto.getBindAnswer().get(0) != null) {
                        stringBuffer.append("答题数量统计").append(JacksonUtils.toJsonString(questionDto.getBindAnswer().get(0).getEvaluateCount())).append("|");
                    }
                }
                item.add(stringBuffer.substring(0, stringBuffer.length() - 1));
            }


            dataList.add(item.toArray(new String[0]));
        }
        POIUtils.exportExcel(hresp, "问卷记录", list.toArray(new String[0]), dataList, "问卷记录");

    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "partySurvey:list")
    @Operation(summary = "分页获取问卷调查管理列表")
    public Response<Page<PartySurveyDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = partySurveyService.queryTotal(request.getParams());

        List<PartySurveyDto> list = null;
        if (total > 0) {
            list = partySurveyService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<PartySurveyDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<PartySurveyDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "partySurvey:edit")
    @Operation(summary = "在编辑时根据id查询问卷调查管理详情")
    public Response<PartySurveyDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (partySurveyService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartySurveyDto partySurveyDto = partySurveyService.selectById(id);

        List<PartySurveyPersonBindingDto> partySurveyPersonBindingDtos = partySurveyPersonBindingService.selectBySurveyId(partySurveyDto.getId());
        partySurveyDto.setBindPerson(partySurveyPersonBindingDtos);

        if (CollectionUtils.isNotEmpty(partySurveyPersonBindingDtos)) {
            List<PartyPersonResp> list = new ArrayList<>();
            for (PartySurveyPersonBindingDto bindPerson : partySurveyDto.getBindPerson()) {
                PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(bindPerson.getPersonId());
                PartyPersonResp result = new PartyPersonResp();
                result.setId(partyPersonDto.getId());
                result.setTenantId(partyPersonDto.getTenantId());
                result.setPartyId(partyPersonDto.getPartyId());
                result.setName(partyPersonDto.getName());
                result.setAvatar(partyPersonDto.getAvatar());
                result.setMobile(partyPersonDto.getMobile());
                list.add(result);
            }
            partySurveyDto.setPersonList(list);
        }

        return Response.<PartySurveyDto>ok().wrap(partySurveyDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "partySurvey:info")
    @Operation(summary = "根据id查询问卷调查管理的详情")
    public Response<PartySurveyDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (partySurveyService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartySurveyDto partySurveyDto = partySurveyService.selectById(id);

        List<PartySurveyPersonBindingDto> partySurveyPersonBindingDtos = partySurveyPersonBindingService.selectBySurveyId(partySurveyDto.getId());
        partySurveyDto.setBindPerson(partySurveyPersonBindingDtos);

        if (CollectionUtils.isNotEmpty(partySurveyPersonBindingDtos)) {
            List<PartyPersonResp> list = new ArrayList<>();
            for (PartySurveyPersonBindingDto bindPerson : partySurveyDto.getBindPerson()) {
                PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(bindPerson.getPersonId());
                PartyPersonResp result = new PartyPersonResp();
                result.setId(partyPersonDto.getId());
                result.setTenantId(partyPersonDto.getTenantId());
                result.setPartyId(partyPersonDto.getPartyId());
                result.setName(partyPersonDto.getName());
                result.setAvatar(partyPersonDto.getAvatar());
                result.setMobile(partyPersonDto.getMobile());
                list.add(result);
            }
            partySurveyDto.setPersonList(list);
        }

        return Response.<PartySurveyDto>ok().wrap(partySurveyDto);
    }

    /**
     * 保存
     *
     * @param partySurveyDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "partySurvey:edit")
    @Operation(summary = "新增问卷调查管理")
    public Response<Object> save(@RequestBody @Validated PartySurveyDto partySurveyDto) {

        //填充基础数据
        fillSaveCommonData(partySurveyDto);
        partySurveyDto.setPartyId(SessionHolder.getSysUser().getPartyId());

        //如果是调查问卷 这几个信息没有 需要填充
        if (PartySurveyConstants.Category.PUBLIC_OPINION_SURVEY.getCategory().equals(partySurveyDto.getCategory())) {
            partySurveyDto.setKnowResult(SystemConstants.NO);
            partySurveyDto.setDayLimit(1);
            partySurveyDto.setPersonLimit(1);
        }

        partySurveyService.saveOrUpdate(partySurveyDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param partySurveyDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "partySurvey:edit")
    @Operation(summary = "根据id修改问卷调查管理")
    public Response<Object> update(@RequestBody @Validated PartySurveyDto partySurveyDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(partySurveyDto.getId()));
        if (partySurveyService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(partySurveyDto);

        //如果是调查问卷 这几个信息没有 需要填充
        if (PartySurveyConstants.Category.PUBLIC_OPINION_SURVEY.getCategory().equals(partySurveyDto.getCategory())) {
            partySurveyDto.setKnowResult(SystemConstants.NO);
            partySurveyDto.setDayLimit(1);
            partySurveyDto.setPersonLimit(1);
        }

        partySurveyService.saveOrUpdate(partySurveyDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "partySurvey:delete")
    @Operation(summary = "根据多条记录id批量删除问卷调查管理")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (partySurveyService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        partySurveyService.deleteBatch(ids);

        return Response.ok();
    }
}
